package org.hamster.multidropbox.mainView.view
{
	import flash.events.MouseEvent;
	import flash.net.FileReference;
	import flash.net.URLLoader;
	
	import mx.collections.ArrayCollection;
	
	import org.hamster.common.puremvc.mediator.BaseMediator;
	import org.hamster.common.utils.ArrayUtils;
	import org.hamster.dropbox.DropboxEvent;
	import org.hamster.dropbox.models.DropboxFile;
	import org.hamster.dropbox.utils.OAuthHelper;
	import org.hamster.multidropbox.dropbox.constants.AppDropboxClientStatus;
	import org.hamster.multidropbox.dropbox.event.AppDropboxEvent;
	import org.hamster.multidropbox.dropbox.vo.AppDropboxClient;
	import org.hamster.multidropbox.dropbox.vo.AppDropboxFile;
	import org.hamster.multidropbox.main.services.AppFileBrowseService;
	import org.hamster.multidropbox.main.services.AppTipService;
	import org.hamster.multidropbox.main.services.StatusBarService;
	import org.hamster.multidropbox.main.utils.AppUtil;
	import org.hamster.multidropbox.mainView.event.AppFileEvent;
	import org.hamster.multidropbox.mainView.event.MainViewEvent;
	
	public class FileListViewMediator extends BaseMediator
	{
		public static const NAME:String = "org.hamster.multidropbox.mainView.view.FileListViewMediator";
		
		private var client:AppDropboxClient;
		
		public function FileListViewMediator(client:AppDropboxClient, viewComponent:Object=null)
		{
			super(NAME + "_" + client.uid.toString(), viewComponent);
			this.client = client;
		}
		
		override public function onRegister():void
		{
			app.addEventListener(AppFileEvent.FILE_PATH_CHANGE, 	       filePathChangeHandler);
			app.addEventListener(MainViewEvent.FILE_ITEM_DOUBLE_CLICK,     fileItemDoubleClickHandler);
			app.addEventListener(MainViewEvent.FILE_ITEM_SHOW_DETIALS,     fileItemShowDetailsHandler);
			app.addEventListener(MainViewEvent.FILE_ITEM_HIDE_DETIALS,     fileItemHideDetailsHandler);
			app.addEventListener(MainViewEvent.UPLOAD_FILE_LOAD_COMPLETE,  uploadFileLoadCompleteHandler);
			client.addEventListener(AppDropboxEvent.CLIENT_STATUS_CHANGED, clientStatusChangeHandler);
		}
		
		override public function onRemove():void
		{
			app.removeEventListener(AppFileEvent.FILE_PATH_CHANGE, 		      filePathChangeHandler);
			app.removeEventListener(MainViewEvent.FILE_ITEM_DOUBLE_CLICK,     fileItemDoubleClickHandler);
			app.removeEventListener(MainViewEvent.FILE_ITEM_SHOW_DETIALS,     fileItemShowDetailsHandler);
			app.removeEventListener(MainViewEvent.FILE_ITEM_HIDE_DETIALS,     fileItemHideDetailsHandler);
			app.removeEventListener(MainViewEvent.UPLOAD_FILE_LOAD_COMPLETE,  uploadFileLoadCompleteHandler);
			client.removeEventListener(AppDropboxEvent.CLIENT_STATUS_CHANGED, clientStatusChangeHandler);
		}
		
		protected function filePathChangeHandler(event:AppFileEvent):void
		{
			var object:Object = {
				path : event.path,
				uid  : client.uid
			};
			this.sendNotification(AppFileEvent.FILE_PATH_CHANGE_REQUEST, object);
		}
		
		protected function fileItemDoubleClickHandler(event:MainViewEvent):void
		{
			var f:AppDropboxFile = event.dropboxFile;
			if (f.isDir) {
				var object:Object = {
					path : f.path,
					uid  : client.uid
				};
				this.sendNotification(AppFileEvent.FILE_PATH_CHANGE_REQUEST, object);
			}
		}
		
		protected function fileItemShowDetailsHandler(event:MainViewEvent):void
		{
			var f:AppDropboxFile = event.dropboxFile;
			StatusBarService.instance.info(
				AppUtil.getStrStatus("status.fileDetails", f.path, f.mimeType, f.modified));
		}
		
		protected function fileItemHideDetailsHandler(event:MainViewEvent):void
		{
			StatusBarService.instance.info("");
		}
		
		protected function uploadFileLoadCompleteHandler(event:MainViewEvent):void
		{
			var appFileBrowseService:AppFileBrowseService = event.data;
			var successList:Array = appFileBrowseService.fileReferenceSuccessList;
			client.addEventListener(DropboxEvent.PUT_FILE_RESULT, clientPutFileResultHandler);
			client.addEventListener(DropboxEvent.PUT_FILE_FAULT, clientPutFileFaultHandler);
			for each (var fileRef:FileReference in successList) {
				var urlLoader:URLLoader = this.client.putFile(app.path.substr(1), fileRef.name, fileRef.data);
				var dropboxFile:DropboxFile = new DropboxFile();
				dropboxFile.isDir = false;
				dropboxFile.bytes = fileRef.size;
				dropboxFile.path = (app.path == "/" ? "/" : app.path + "/") + fileRef.name;
				var newAppDropboxFile:AppDropboxFile = new AppDropboxFile(this.client, dropboxFile);
				newAppDropboxFile.loader = urlLoader;
				this.app.fileList.addItem(newAppDropboxFile);
			}
		}
		
		protected function clientPutFileResultHandler(event:DropboxEvent):void
		{
			this.client.removeEventListener(DropboxEvent.PUT_FILE_RESULT, clientPutFileResultHandler);
			this.client.removeEventListener(DropboxEvent.PUT_FILE_FAULT, clientPutFileFaultHandler);
			var newDropboxFile:DropboxFile = event.resultObject as DropboxFile;
			var appDropboxFile:AppDropboxFile = new AppDropboxFile(client, newDropboxFile);
			for each (var curDropboxFile:AppDropboxFile in this.app.fileList) {
				if (curDropboxFile.path == appDropboxFile.path) {
					app.fileList.removeItemAt(app.fileList.getItemIndex(curDropboxFile));
				}
			}
			app.fileList.addItem(appDropboxFile);
		}
		
		protected function clientPutFileFaultHandler(event:DropboxEvent):void
		{
			this.client.removeEventListener(DropboxEvent.PUT_FILE_RESULT, clientPutFileResultHandler);
			this.client.removeEventListener(DropboxEvent.PUT_FILE_FAULT, clientPutFileFaultHandler);
		}
		
		protected function clientStatusChangeHandler(event:AppDropboxEvent):void
		{
			if (event.newStatus == AppDropboxClientStatus.AVAILABLE) {
				var object:Object = {
					path : "",
					uid  : client.uid
				};
				this.sendNotification(AppFileEvent.FILE_PATH_CHANGE_REQUEST, object);
			}
		}
		
		public function get uid():int
		{
			return client.uid;
		}
		
		override public function listNotificationInterests():Array
		{
			return [
				AppDropboxEvent.DROPBOX_METADATA_RESULT,
				AppDropboxEvent.DROPBOX_METADATA_FAULT,
			];
		}
		
		public function handleDropboxMetadataResult(data:Object):void
		{
			app.selectedItemRendererIndex = 0;
			var dropboxFile:AppDropboxFile = data as AppDropboxFile;
			if (dropboxFile.client.uid == this.client.uid) {
				app.path = dropboxFile.path;
				app.fileList = new ArrayCollection(ArrayUtils.clone(dropboxFile.contents));
			}
		}
		
		public function handleDropboxMetadataFault(data:Object):void
		{
			var title:String = AppUtil.getStrStatus("tip.getMetadataFailed.title");
			var text:String  = AppUtil.getStrStatus("tip.getMetadataFailed.text", data);
			AppTipService.instance.error(title, text);
		}
		
		public function get app():FileListView
		{
			return viewComponent as FileListView;
		}
	}
}